import React, { useState, useEffect } from "react";
import { Modal, Form, Input, Select, DatePicker, message } from "antd";
import { useAppDispatch, useAppSelector } from "../../../hooks/redux";
import { createTask } from "../../../store/projectSlice";
import { TaskPriority } from "../../../types/project";
import { mockProjectApi } from "../../../api/mockProjectApi";
import dayjs from "dayjs";

const { TextArea } = Input;
const { Option } = Select;

interface CreateTaskModalProps {
  /** 弹窗是否可见 */
  visible: boolean;
  /** 取消回调 */
  onCancel: () => void;
  /** 成功创建回调 */
  onSuccess: () => void;
  /** 默认分组ID（可选） */
  defaultGroupId?: string;
  /** 项目ID（可选，用于指定分组选项） */
  projectId?: string;
}

/**
 * 新建任务弹窗组件
 * 提供表单让用户输入任务信息并创建新任务
 */
const CreateTaskModal: React.FC<CreateTaskModalProps> = ({
  visible,
  onCancel,
  onSuccess,
  defaultGroupId,
  projectId
}) => {
  const dispatch = useAppDispatch();
  const { currentProject } = useAppSelector(state => state.project);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState<any[]>([]);

  /**
   * 获取用户列表（用于负责人选择）
   */
  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const userList = await mockProjectApi.getUsers();
        setUsers(userList);
      } catch (error) {
        console.error("获取用户列表失败:", error);
      }
    };

    if (visible) {
      fetchUsers();
    }
  }, [visible]);

  /**
   * 处理表单提交
   * @param values 表单数据
   */
  const handleSubmit = async (values: any) => {
    if (!currentProject && !projectId) {
      message.error("请先选择项目");
      return;
    }

    if (users.length === 0) {
      message.error("用户数据加载失败，请刷新页面重试");
      return;
    }

    setLoading(true);
    try {
      // 构建任务数据
      const taskData = {
        title: values.title,
        description: values.description,
        priority: values.priority || TaskPriority.MEDIUM,
        assignee: values.assigneeId ? users.find(u => u.id === values.assigneeId) : undefined,
        creator: users.length > 0 ? users[0] : { id: "default", name: "默认用户", avatar: "" }, // 安全的默认创建者
        startDate: values.startDate?.toISOString(),
        dueDate: values.dueDate?.toISOString(),
        milestone: values.milestone,
        tags: values.tags || []
      };

      // 确定目标分组ID
      const targetGroupId = values.groupId || defaultGroupId || currentProject?.groups[0]?.id;
      if (!targetGroupId) {
        console.error("无法确定任务分组:", {
          valuesGroupId: values.groupId,
          defaultGroupId,
          currentProjectGroups: currentProject?.groups?.map(g => ({ id: g.id, title: g.title })),
          projectId: projectId || currentProject?.id
        });
        message.error("无法确定任务分组");
        return;
      }

      // 创建任务
      await dispatch(
        createTask({
          projectId: projectId || currentProject!.id,
          groupId: targetGroupId,
          taskData
        })
      ).unwrap();

      message.success("任务创建成功");
      form.resetFields();
      onSuccess();
    } catch (error) {
      console.error("创建任务失败:", error);
      message.error("创建任务失败，请重试");
    } finally {
      setLoading(false);
    }
  };

  /**
   * 处理弹窗关闭
   */
  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  /**
   * 优先级选项
   */
  const priorityOptions = [
    { value: TaskPriority.LOW, label: "低优先级", color: "#87d068" },
    { value: TaskPriority.MEDIUM, label: "中优先级", color: "#108ee9" },
    { value: TaskPriority.HIGH, label: "高优先级", color: "#f50" },
    { value: TaskPriority.URGENT, label: "紧急", color: "#ff4d4f" }
  ];

  /**
   * 里程碑选项
   */
  const milestoneOptions = [
    "M0 - 项目启动",
    "M1 - 需求确认",
    "M1 - 技术选型",
    "M2 - 环境搭建",
    "M2 - 设计完成",
    "M3 - 核心功能",
    "M4 - 测试验收",
    "M5 - 上线发布"
  ];

  return (
    <Modal
      title="新建任务"
      open={visible}
      onCancel={handleCancel}
      onOk={() => form.submit()}
      confirmLoading={loading}
      okText="创建任务"
      cancelText="取消"
      width={600}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        initialValues={{
          priority: TaskPriority.MEDIUM,
          groupId: defaultGroupId
        }}
      >
        {/* 任务标题 */}
        <Form.Item
          name="title"
          label="任务标题"
          rules={[
            { required: true, message: "请输入任务标题" },
            { max: 100, message: "标题不能超过100个字符" }
          ]}
        >
          <Input placeholder="请输入任务标题" />
        </Form.Item>

        {/* 任务描述 */}
        <Form.Item name="description" label="任务描述" rules={[{ max: 500, message: "描述不能超过500个字符" }]}>
          <TextArea placeholder="请输入任务描述（可选）" rows={3} showCount maxLength={500} />
        </Form.Item>

        {/* 第一行：分组和优先级 */}
        <div className="flex gap-4">
          {/* 所属分组 */}
          {currentProject && (
            <Form.Item
              name="groupId"
              label="所属分组"
              className="flex-1"
              rules={[{ required: true, message: "请选择任务分组" }]}
            >
              <Select placeholder="请选择分组">
                {currentProject.groups.map(group => (
                  <Option key={group.id} value={group.id}>
                    <div className="flex items-center gap-2">
                      <div className="w-3 h-3 rounded-full" style={{ backgroundColor: group.color }} />
                      {group.title}
                    </div>
                  </Option>
                ))}
              </Select>
            </Form.Item>
          )}

          {/* 优先级 */}
          <Form.Item name="priority" label="优先级" className="flex-1">
            <Select placeholder="请选择优先级">
              {priorityOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  <div className="flex items-center gap-2">
                    <div className="w-3 h-3 rounded-full" style={{ backgroundColor: option.color }} />
                    {option.label}
                  </div>
                </Option>
              ))}
            </Select>
          </Form.Item>
        </div>

        {/* 第二行：负责人和里程碑 */}
        <div className="flex gap-4">
          {/* 负责人 */}
          <Form.Item name="assigneeId" label="负责人" className="flex-1">
            <Select placeholder="请选择负责人" allowClear>
              {users.map(user => (
                <Option key={user.id} value={user.id}>
                  <div className="flex items-center gap-2">
                    <img src={user.avatar} alt={user.name} className="w-4 h-4 rounded-full" />
                    {user.name}
                  </div>
                </Option>
              ))}
            </Select>
          </Form.Item>

          {/* 里程碑 */}
          <Form.Item name="milestone" label="里程碑" className="flex-1">
            <Select placeholder="请选择里程碑" allowClear>
              {milestoneOptions.map(milestone => (
                <Option key={milestone} value={milestone}>
                  {milestone}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </div>

        {/* 第三行：开始时间和截止时间 */}
        <div className="flex gap-4">
          {/* 开始时间 */}
          <Form.Item name="startDate" label="开始时间" className="flex-1">
            <DatePicker
              placeholder="选择开始时间"
              className="w-full"
              format="YYYY-MM-DD"
              disabledDate={current => current && current < dayjs().startOf("day")}
            />
          </Form.Item>

          {/* 截止时间 */}
          <Form.Item
            name="dueDate"
            label="截止时间"
            className="flex-1"
            dependencies={["startDate"]}
            rules={[
              ({ getFieldValue }) => ({
                validator(_, value) {
                  const startDate = getFieldValue("startDate");
                  if (!value || !startDate) {
                    return Promise.resolve();
                  }
                  if (value.isBefore(startDate)) {
                    return Promise.reject(new Error("截止时间不能早于开始时间"));
                  }
                  return Promise.resolve();
                }
              })
            ]}
          >
            <DatePicker
              placeholder="选择截止时间"
              className="w-full"
              format="YYYY-MM-DD"
              disabledDate={current => current && current < dayjs().startOf("day")}
            />
          </Form.Item>
        </div>

        {/* 标签 */}
        <Form.Item name="tags" label="标签">
          <Select mode="tags" placeholder="输入标签，按回车添加" tokenSeparators={[","]} maxTagCount={5} />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CreateTaskModal;
